import axios from 'axios'
import * as types from './mutation-types'
import tool from '@/commons/libraries/tool'

export const signIn = ({commit}, user) =>{
  return new Promise((resolve, reject) =>{
    commit(types.USER_SING_IN, user)
    tool.saveLocalStorage('jwt', user.jwt)
    tool.saveLocalStorage('name', user.name)
    axios.defaults.headers.common['Jwt'] = user.jwt
    resolve(true)
  })
}
export const signOut = ({commit}) =>{
  return new Promise((resolve, reject) =>{
    commit(types.USER_SIGN_OUT)
    tool.clearLocalStorage()
    axios.defaults.headers.common['Jwt'] = ''
    resolve(true)
  })
}
export const isSign = (context) =>{
  return new Promise((resolve, reject) =>{
    if(!tool.isEmpty(context.getters.jwt)){
      resolve(true)
    }else{
      let jwt = tool.getLocalStorage('jwt')
      let name = tool.getLocalStorage('name')
      if(!tool.isEmpty(jwt)){
        context.commit(types.USER_SING_IN, {
          jwt: jwt,
          name: name
        })
        axios.defaults.headers.common['Jwt'] = jwt
        resolve(true)
      }
    }
    resolve(false)
  })
}
